import React, {useState, useEffect} from 'react';
import {Breadcrumb} from 'antd';
import {ProBreadcrumbContainer} from './style';
import {useLocation} from 'react-router-dom';
import {Link} from 'react-router-dom';


const pathMap: any = {
    '/conference': ['home', 'conference'],
    '/conference/add': ['home', 'conference', 'add'],
    '/test': ['home', 'test'],
};

function ProBreadcrumb() {

    const [currentPathArr, setCurrentPathArr] = useState<string[]>([]);

    const {pathname} = useLocation();

    useEffect(() => {
        if (pathMap[pathname]) {
            setCurrentPathArr(pathMap[pathname]);
        } else {
            setCurrentPathArr([]);
        }
    }, [pathname]);

    const BreadcrumbItem: any = () => {
        const currentLen = currentPathArr.length - 1;
        return currentPathArr.map((item: string, index: number) => {
            if (currentLen === index) {
                return (
                    <Breadcrumb.Item
                        key={index + item}
                    >
                        {item}
                    </Breadcrumb.Item>
                )
            } else {
                return (
                    <Breadcrumb.Item
                        key={index + item}
                    >
                        <Link to={'/' + item}>
                            {item}
                        </Link>
                    </Breadcrumb.Item>
                )
            }
        })
    };
    const renderBreadcrumb = () => {
        return (
            <ProBreadcrumbContainer>
                <Breadcrumb>
                    { BreadcrumbItem() }
                </Breadcrumb>
            </ProBreadcrumbContainer>
        )
    };
    return (
        <>
        {
            currentPathArr.length > 0 ? renderBreadcrumb() : null
        }
        </>
    )
}

export default React.memo(ProBreadcrumb);
